<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <el-affix :offset="10">
          <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
            <el-radio-button :value="false">展开</el-radio-button>
            <el-radio-button :value="true">折叠</el-radio-button>
          </el-radio-group>
          <el-menu default-active="1" class="el-menu-vertical-demo" :collapse="isCollapse" @open="handleOpen"
            @close="handleClose" @select="handleSelect">
            <el-menu-item index="/index">
              <el-icon>
                <House />
              </el-icon>
              <template #title>首页 </template>
            </el-menu-item>
            <el-menu-item index="/booklist">
              <el-icon>
                <Folder />
              </el-icon>
              <template #title>图书列表</template>
            </el-menu-item>
            <el-menu-item index="/booksales">
              <el-icon>
                <Reading />
              </el-icon>
              <template #title>图书售卖</template>
            </el-menu-item>
            <el-menu-item index="/help">
              <el-icon>
                <Warning />
              </el-icon>
              <template #title>帮助</template>
            </el-menu-item>
          </el-menu>
          <!-- 路由出口，用于显示当前路由对应的组件 -->
          <router-view></router-view>
        </el-affix>
      </el-aside>
      <el-container>
        <el-affix :offset="0">
          <el-header style="
              display: flex;
              align-items: center;
              height: 60px;
              border: 1px solid #f5f6fe;
            ">
            <!-- 添加 flex-grow: 1 使该 div 占据剩余空间 -->
            <div style="flex-grow: 1"></div>

            <router-link to="/cart" style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
                text-decoration: none; /* 去除默认下划线 */
                color: inherit; /* 继承父元素颜色 */
              ">
              <el-badge :value="bookStore.orderedBooksCount" :max="10" class="badge-item">
                <span class="icon-wrapper">
                  <el-icon style="font-size: 25px">
                    <ShoppingCart />
                  </el-icon>
                </span>
              </el-badge>
            </router-link>

            <div style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
              ">
              <span class="icon-wrapper">
                <el-icon style="font-size: 25px">
                  <Setting />
                </el-icon>
              </span>
            </div>

            <div style="padding-right: 20px">
              <el-popover placement="bottom" trigger="hover">
                <el-menu mode="vertical">
                  <el-menu-item index="1" @click="handleMenuItemClick(1)">个人中心</el-menu-item>
                  <el-menu-item index="2" @click="handleMenuItemClick(2)">关于我们</el-menu-item>
                  <el-menu-item index="3" @click="handleMenuItemClick_exit(3)">退出登录</el-menu-item>
                </el-menu>

                <template #reference>
                  <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                </template>
              </el-popover>
            </div>
          </el-header>
        </el-affix>
        <el-main>
          <h3 style="text-align: left">图书售卖</h3>

          <el-row>
            <el-col :span="24">
              <div class="grid-content">
                <div class="time-container">
                  <h2>图书售卖列表</h2>
                  <!-- 卡片的内容，显示格式化后的时间 -->
                  <div>{{ formattedTime }}</div>
                </div>

                <div class="statisticalBooks">
                  <el-button type="success" :icon="Plus" @click="openDialog">添加售出图书</el-button>
                  <span style="margin-left: 10px">正在售卖的书籍数量:
                    <span class="red-text">{{ sellingBookCount }} </span></span>
                  <span style="margin-left: 10px">
                    已售出的书籍数量:
                    <span class="green-text">{{ deletedBookCount }}</span></span>
                </div>

                <!-- 对话框 -->
                <el-dialog v-model="dialogVisible" title="添加图书信息">
                  <el-form :model="bookForm" label-width="80px">
                    <el-form-item label="图书名称">
                      <el-input v-model="bookForm.bookName"></el-input>
                    </el-form-item>
                    <el-form-item label="作者">
                      <el-input v-model="bookForm.author"></el-input>
                    </el-form-item>
                    <el-form-item label="图书编号">
                      <el-input v-model="bookForm.bookNumber"></el-input>
                    </el-form-item>
                    <el-form-item label="售出时间">
                      <el-date-picker v-model="bookForm.saleTime" type="datetime" placeholder="选择售出时间"></el-date-picker>
                    </el-form-item>
                  </el-form>

                  <template #footer>
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                  </template>
                </el-dialog>

                <!-- 显示表单信息 -->
                <div v-if="bookList.length > 0">
                  <el-table :data="bookList">
                    <el-table-column prop="bookName" label="图书名称"></el-table-column>
                    <el-table-column prop="author" label="作者"></el-table-column>
                    <el-table-column prop="bookNumber" label="图书编号"></el-table-column>
                    <el-table-column prop="saleTime" label="售出时间">
                      <template #default="scope">
                        {{ formatDate(scope.row.saleTime) }}
                      </template>
                    </el-table-column>
                    <el-table-column label="操作">
                      <template #default="scope">
                        <el-button type="primary" size="small" @click="editBook(scope.row)">编辑</el-button>
                        <el-button type="success" size="small" @click="soldBook(scope.$index)">已售出</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                <div>
                  <div class="time-container">
                    <h2>已完成售出</h2>
                  </div>
                  <!-- 显示已售出的书籍信息 -->
                  <div v-if="soldBookList.length > 0">
                    <el-table :data="soldBookList">
                      <el-table-column prop="bookName" label="图书名称"></el-table-column>
                      <el-table-column prop="author" label="作者"></el-table-column>
                      <el-table-column prop="bookNumber" label="图书编号"></el-table-column>
                      <el-table-column prop="saleTime" label="售出时间">
                        <template #default="scope">
                          {{ formatDate(scope.row.saleTime) }}
                        </template>
                      </el-table-column>
                      <el-table-column label="操作">
                        <template #default="scope">
                          <el-button type="danger" size="small" @click="deleteBook(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-main>
        <el-footer style="
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
          ">
          <div>Designed with by XXX</div>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>


<script lang="ts" setup>
import { reactive } from "vue";
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import {
  Reading,
  House,
  Warning,
  Folder,
  Search,
  ArrowRight,
  CaretBottom,
  CaretTop,
  Top,
  Bottom,
  Close,
  Setting,
  ShoppingCart,
  Plus,
} from "@element-plus/icons-vue";
import type { TabsPaneContext } from "element-plus";
import { useRouter } from "vue-router";
import {
  ElPopover,
  ElAvatar,
  ElMenu,
  ElMenuItem,
  ElMessage,
  ElMessageBox,
} from "element-plus";
import dayjs from "dayjs";

import "../mock/iconfont.js";
import { useLogout } from "../composables/useLogout";
import { useBookStore } from '../stores/bookStore';

const router = useRouter();
const bookStore = useBookStore();

// 定义一个响应式变量来存储格式化后的时间
const formattedTime = ref("");

// 定义一个定时器变量
let timer: number;

// 定义一个数组来存储星期几的中文表示
const weekDays = [
  "星期日",
  "星期一",
  "星期二",
  "星期三",
  "星期四",
  "星期五",
  "星期六",
];

// 定义一个函数来更新时间
const updateTime = () => {
  const now = new Date();
  // 获取年、月、日
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  // 格式化时间为 HH:mm:ss 的格式
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  formattedTime.value = `${hours}:${minutes}:${seconds}`;
  // 获取星期几
  const weekDay = weekDays[now.getDay()];
  // 拼接成所需的时间格式
  formattedTime.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds} ${weekDay}`;
};

// 在组件挂载时启动定时器
onMounted(() => {
  // 立即更新一次时间
  updateTime();
  // 每秒更新一次时间
  timer = setInterval(updateTime, 1000);
});

// 在组件卸载时清除定时器
onUnmounted(() => {
  clearInterval(timer);
});

onMounted(() => {
  const userData = localStorage.getItem("userData");
  if (!userData) {
    // 如果没有获取到数据，跳转到登录页
    router.push("/login");
  }
});

// 定义书籍对象的类型
type Book = {
  author: string;
  bookName: string;
  bookNumber: string;
  saleTime: Date | null;
};

const isCollapse = ref(false);

// 创建一个响应式的布尔变量，初始值设为true，表示div初始是可见的
const isDivVisible = ref(true);

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

const handleSelect = (key: string) => {
  // 根据菜单项的 index 值切换页面

  router.push(key);
};

const handleMenuItemClick = (index: number) => {
  console.log(`你点击了选项 ${index}`);
};

const { isLoading, logout } = useLogout();
const handleMenuItemClick_exit = async (index: number) => {
  console.log(`你点击了选项 ${index}`);
  await logout();
};

// 对话框显示状态
const dialogVisible = ref(false);
// 表单数据
const bookForm = ref<Book>({
  bookName: "",
  author: "",
  bookNumber: "",
  saleTime: null,
});
// 图书列表
const bookList = ref<Book[]>([]);
// 当前编辑的图书索引
const currentEditIndex = ref(-1);
// 正在售卖的书籍数量
const sellingBookCount = ref(0);
// 已售出的书籍列表
const soldBookList = ref<Book[]>([]);
// 已删除的书籍数量
const deletedBookCount = ref(0);

// 监听 bookList 的变化，更新正在售卖的书籍数量
watch(
  bookList,
  () => {
    sellingBookCount.value = bookList.value.length;
    console.log(sellingBookCount.value);
  },
  { deep: true }
);

// 监听 soldBookList 的变化，更新已删除的书籍数量
watch(
  soldBookList,
  () => {
    deletedBookCount.value = soldBookList.value.length;
  },
  { deep: true }
);

// 打开对话框
const openDialog = (): void => {
  // 清空表单
  bookForm.value = {
    bookName: "",
    author: "",
    bookNumber: "",
    saleTime: null,
  };
  currentEditIndex.value = -1;
  dialogVisible.value = true;
};

// 提交表单
const submitForm = (): void => {
  if (currentEditIndex.value !== -1) {
    // 修改图书信息
    bookList.value[currentEditIndex.value] = { ...bookForm.value };
  } else {
    // 添加新图书
    const newBook: Book = { ...bookForm.value };
    bookList.value.push(newBook);
  }
  // 清空表单
  bookForm.value = {
    bookName: "",
    author: "",
    bookNumber: "",
    saleTime: null,
  };
  // 关闭对话框
  dialogVisible.value = false;
  currentEditIndex.value = -1;
};

// 编辑图书
const editBook = (book: Book): void => {
  currentEditIndex.value = bookList.value.findIndex(
    (item) => item.bookNumber === book.bookNumber
  );
  bookForm.value = { ...book };
  dialogVisible.value = true;
};

// 已售图书
const soldBook = (index: number): void => {
  const soldBook = bookList.value.splice(index, 1)[0];
  soldBookList.value.push(soldBook);
};

// 删除图书
const deleteBook = (index: number): void => {
  soldBookList.value.splice(index, 1);
};

// 格式化日期
const formatDate = (date: Date | null): string => {
  return date ? dayjs(date).format("YYYY-MM-DD HH:mm:ss") : "";
};
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-header {
  /* background-color: gray; */
  background-color: #fff;
}

.el-aside {
  background-color: #fff;
  /* background-color: pink; */
  border: 1px solid #f5f6fe;
}

.el-main {
  background-color: #f5f6fe;
  /* background-color: orange; */
}

.el-menu {
  border-right: none;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.grid-content {
  border-radius: 4px;
  min-height: 400px;
  background-color: #fff;
}

:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}

p {
  margin: 0;
  padding: 0;
  font-size: 14px;
  text-align: left;
}

.p-vertically-center {
  display: flex;
  /* 使用 Flexbox 布局 */
  flex-direction: column;
  /* 垂直排列子元素 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中 */
  height: 100%;
  /* 确保容器有高度 */
}

.p-vertically-center p {
  margin: 5px 40px;
  /* 为每个段落添加上下外边距 */
}

/* Vue 3 中使用 ::v-deep 穿透样式，将所有标签页标题文字加粗 */
::v-deep .el-tabs__item {
  font-weight: bold;
}

/* 确保弹出框有最小宽度 */
.el-popover {
  min-width: 120px;
  z-index: 1000;
  /* 确保弹出框显示在最上层 */
}

.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.overflow-menu-icon {
  float: right;
  cursor: pointer;
  font-size: 20px;
}

.message-box-content {
  white-space: pre-line;
}

.time-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px 0 20px;
}

.statisticalBooks {
  text-align: left;
  padding: 0 20px 0 20px;
}

.red-text {
  color: red;
}

.green-text {
  color: green;
}

.badge-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>